<template>
  <ElectronWindowsControlButtonView :maximizable="false" />

  <div class="page flex flex-rr flex-cc">
    <div class="box flex flex-col flex-rb">
      <div class="top">
        <!-- logo -->
        <div class="logo flex flex-center">
          <img src="@/kang/img/logo.png" />
        </div>

        <!-- 登录 -->
        <div class="form" v-if="formType === 1">
          <div class="title">登录</div>

          <div class="row">
            <div class="label">账号</div>
            <div class="input">
              <n-input
                placeholder="请输入账号"
                v-model:value="model.account"
              ></n-input>
            </div>
          </div>

          <div class="row">
            <div class="label">密码</div>
            <div class="input">
              <n-input
                type="password"
                placeholder="请输入密码"
                v-model:value="model.password"
              ></n-input>
            </div>
          </div>

          <div class="flex flex-rb">
            <div class="cl-primary click" @click="changeFormType(2)">
              没有账号？立即注册
            </div>
            <div class="cl-primary click" @click="changeFormType(3)">
              忘记密码
            </div>
          </div>
        </div>

        <!-- 注册 -->
        <div class="form" v-else-if="formType === 2">
          <div class="title">欢迎注册</div>

          <div class="row">
            <div class="label">账号</div>
            <div class="input">
              <n-input
                placeholder="请输入账号"
                v-model:value="model.account"
              ></n-input>
            </div>
          </div>

          <div class="row">
            <div class="label">密码</div>
            <div class="input">
              <n-input
                type="password"
                placeholder="请输入密码"
                v-model:value="model.password"
              ></n-input>
            </div>
          </div>

          <div class="row">
            <div class="label">邀请码</div>
            <div class="input">
              <n-input
                type="password"
                placeholder="请输入邀请码"
                v-model:value="model.code"
              ></n-input>
            </div>
          </div>

          <div class="flex flex-rb">
            <div class="cl-primary click" @click="changeFormType(1)">
              已有账号？立即登录
            </div>
          </div>
        </div>

        <!-- 忘记密码 -->
        <div class="form" v-else-if="formType === 3">
          <div class="title">重置密码</div>

          <template v-if="resetStep === 1">
            <div class="row">
              <div class="label">账号</div>
              <div class="input">
                <n-input
                  placeholder="请输入账号"
                  v-model:value="model.account"
                ></n-input>
              </div>
            </div>

            <div class="row">
              <div class="label">密保邮箱</div>
              <div class="input">
                <n-input
                  placeholder="请输入密保邮箱"
                  v-model:value="model.email"
                ></n-input>
              </div>
            </div>
          </template>

          <template v-else-if="resetStep === 2">
            <div class="row">
              <div class="label">邮箱验证码</div>
              <div class="input">
                <n-input
                  placeholder="请输入邮箱验证码"
                  v-model:value="model.emailCode"
                ></n-input>
              </div>
            </div>
          </template>

          <template v-else-if="resetStep === 3">
            <div class="row">
              <div class="label">新密码</div>
              <div class="input">
                <n-input
                  type="password"
                  placeholder="请输入新密码"
                  v-model:value="model.newPassword"
                ></n-input>
              </div>
            </div>
          </template>

          <div class="flex flex-rb">
            <div class="cl-primary click" @click="changeFormType(1)">
              已有账号？立即登录
            </div>
          </div>
        </div>
      </div>

      <div class="bottom">
        <n-button
          type="primary"
          block
          :disabled="!model.account || !model.password"
          :loading="loading"
          @click="login"
          v-if="formType === 1"
        >
          立即登录
        </n-button>

        <n-button
          type="primary"
          block
          :disabled="!model.account || !model.password || !model.code"
          :loading="loading"
          @click="register"
          v-else-if="formType === 2"
        >
          立即注册
        </n-button>

        <template v-else-if="formType === 3">
          <n-button
            type="primary"
            block
            :disabled="!model.account || !model.email"
            :loading="loading"
            @click="sendEmailCode"
            v-if="resetStep === 1"
          >
            下一步
          </n-button>

          <n-button
            type="primary"
            block
            :disabled="!model.emailCode"
            :loading="loading"
            @click="verifyEmailCode"
            v-else-if="resetStep === 2"
          >
            下一步
          </n-button>

          <n-button
            type="primary"
            block
            :disabled="!model.newPassword"
            :loading="loading"
            @click="resetPassword"
            v-else-if="resetStep === 3"
          >
            立即重置
          </n-button>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import wfc from '@/wfc/client/wfc'
import EventType from '@/wfc/client/wfcEvent'
import IpcEventType from '@/ipcEventType'
import ConnectionStatus from '@/wfc/client/connectionStatus'
import { ipcRenderer, isElectron } from '@/platform'
import { getItem, setItem } from '@/ui/util/storageHelper'
import api from '@/kang/js/api'

import ElectronWindowsControlButtonView from '../common/ElectronWindowsControlButtonView.vue'

const router = useRouter()

const model = ref({
  account: 'xielikang',
  password: 'kangjs123',
  code: '112211',
  email: '839626987@qq.com',
  emailCode: '',
  newPassword: 'kangjs123',
})

const formType = ref(1)
const resetStep = ref(1)
const loading = ref(false)

onMounted(() => {
  wfc.eventEmitter.on(
    EventType.ConnectionStatusChanged,
    onConnectionStatusChange
  )

  const userId = getItem('userId')
  const imToken = getItem('imToken')

  if (userId) {
    if (imToken) {
      wfc.connect(userId, imToken)
    } else {
      isElectron() && ipcRenderer.send(IpcEventType.RESIZE_LOGIN_WINDOW)
    }
  } else {
    isElectron() && ipcRenderer.send(IpcEventType.RESIZE_LOGIN_WINDOW)
  }
})

onUnmounted(() => {
  wfc.eventEmitter.removeListener(
    EventType.ConnectionStatusChanged,
    onConnectionStatusChange
  )
})

// 登录
async function login() {
  try {
    const params = {
      account: model.value.account,
      password: model.value.password,
    }

    loading.value = true
    const { code, data } = await api.login(params)
    loading.value = false

    if (code === 200) {
      $message.success('登录成功')
      const { userId, imToken, token, portrait = '' } = data
      wfc.connect(userId, imToken)
      setItem('userId', userId)
      setItem('imToken', imToken)
      setItem('token', token)
      setItem('userPortrait', portrait)
    }
  } catch (err) {
    console.error(err)
    loading.value = false
  }
}

// 注册
async function register() {
  try {
    const params = {
      account: model.value.account,
      password: model.value.password,
      code: model.value.code,
    }

    loading.value = true
    const { code } = await api.register(params)
    loading.value = false

    if (code === 200) {
      changeFormType(1)
      $message.success('注册成功')
    }
  } catch (err) {
    console.error(err)
    loading.value = false
  }
}

// 发送邮箱验证码
async function sendEmailCode() {
  try {
    const params = {
      account: model.value.account,
      email: model.value.email,
    }

    loading.value = true
    const { code } = await api.sendEmailCode(params)
    loading.value = false

    if (code === 200) {
      resetStep.value = 2
      $message.success('发送成功')
    }
  } catch (err) {
    console.error(err)
    loading.value = false
  }
}

// 验证邮箱验证码
async function verifyEmailCode() {
  try {
    const params = {
      account: model.value.account,
      code: model.value.emailCode,
    }

    loading.value = true
    const { code, data } = await api.verifyEmailCode(params)
    loading.value = false

    if (code === 200) {
      model.value.authToken = data.authToken
      resetStep.value = 3
      $message.success('验证成功')
    }
  } catch (err) {
    console.error(err)
    loading.value = false
  }
}

// 重置密码
async function resetPassword() {
  try {
    const params = {
      newPassword: model.value.newPassword,
      authToken: model.value.authToken,
    }

    loading.value = true
    const { code } = await api.resetPassword(params)
    loading.value = false

    if (code === 200) {
      changeFormType(1)
      $message.success('重置成功')
    }
  } catch (err) {
    console.error(err)
    loading.value = false
  }
}

function changeFormType(e) {
  formType.value = e
}

function onConnectionStatusChange(status) {
  if (
    status === ConnectionStatus.ConnectionStatusLogout ||
    status === ConnectionStatus.ConnectionStatusRejected ||
    status === ConnectionStatus.ConnectionStatusSecretKeyMismatch ||
    status === ConnectionStatus.ConnectionStatusKickedOff ||
    status === ConnectionStatus.ConnectionStatusNotLicensed ||
    status === ConnectionStatus.ConnectionStatusTimeInconsistent ||
    status === ConnectionStatus.ConnectionStatusServerDown ||
    status === ConnectionStatus.ConnectionStatusUnconnected ||
    status === ConnectionStatus.ConnectionStatusTokenIncorrect
  ) {
    if (status !== ConnectionStatus.ConnectionStatusLogout) {
      console.error('连接失败', status, ConnectionStatus.desc(status))
      $message.error('连接失败，请打开控制台，查看具体日志')
    }
  }

  if (status === ConnectionStatus.ConnectionStatusReceiveing) {
    $message.info('数据同步中，可能需要数分钟')
  }

  if (status === ConnectionStatus.ConnectionStatusConnected) {
    if (isElectron()) {
      ipcRenderer.send(IpcEventType.LOGIN, {
        closeWindowToExit:
          getItem(wfc.getUserId() + '-' + 'closeWindowToExit') === '1',
      })
    }

    if (
      isElectron() ||
      Config.CLIENT_ID_STRATEGY === 1 ||
      Config.CLIENT_ID_STRATEGY === 2
    ) {
      isElectron() &&
        ipcRenderer.send(IpcEventType.LOGIN, {
          userId: wfc.getUserId(),
          closeWindowToExit:
            getItem(wfc.getUserId() + '-' + 'closeWindowToExit') === '1',
        })
    }

    router.replace({ path: '/home' })
  }
}
</script>

<style lang="scss" scoped>
.page {
  height: calc(100% - 31px);
  padding-right: 100px;
  background: url('@/kang/img/login_bg.png') no-repeat center / cover;

  .box {
    width: 370px;
    height: 520px;
    background-color: var(--color-white);
    padding: 0 50px 20px;
    border-radius: 20px;
  }

  .top {
    .logo {
      img {
        width: 100px;
      }
    }

    .form {
      .title {
        font-size: 20px;
        font-weight: bolder;
        margin-bottom: 15px;
      }

      .row {
        margin-bottom: 15px;

        .label {
          margin-bottom: 5px;
        }

        .input {
          :deep(.n-input) {
            height: 40px;
            background-color: var(--color-bg);

            input {
              height: 40px;
            }

            .n-input__border {
              opacity: 0;
            }
          }
        }
      }

      .click {
        font-size: 12px;
      }
    }
  }

  .bottom {
    :deep(.n-button) {
      height: 50px;
    }
  }
}
</style>
